package com.bndg.blackjack.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.bndg.blackjack.AppUtils
import com.bndg.blackjack.R
/**
 * @author r
 * @date 2024/12/10
 * @description 可动态设置圆角的view
 */

class CircleTransitionView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private var borderRadius = 0f
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var text: String = "" // 默认文字

    init {
        // 从 XML 中获取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleTransitionView)
        borderRadius = typedArray.getDimension(R.styleable.CircleTransitionView_borderRadius, 0f)
        text = typedArray.getString(R.styleable.CircleTransitionView_text) ?: ""
        paint.color = typedArray.getColor(R.styleable.CircleTransitionView_bgColor, Color.BLUE)
        textPaint.textSize = typedArray.getDimension(R.styleable.CircleTransitionView_textSize, AppUtils.sp2px(35f) * 1.0f)
        typedArray.recycle()

        // 设置画笔的颜色和填充样式
        paint.style = Paint.Style.FILL

        // 设置文字画笔的样式
        textPaint.color = Color.WHITE
        textPaint.textAlign = Paint.Align.CENTER // 设置文字居中显示
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 绘制圆角矩形或圆形
        canvas.drawRoundRect(
            0f,
            0f,
            width.toFloat(),
            height.toFloat(),
            borderRadius,
            borderRadius,
            paint
        )

        // 计算文字的纵向基线，使文字垂直居中
        val textX = width / 2f
        val textY = height / 2f - (textPaint.descent() + textPaint.ascent()) / 2

        // 绘制文字
        canvas.drawText(text, textX, textY, textPaint)
    }

    // 设置圆角半径的值
    fun setRadius(radius: Float) {
        borderRadius = radius
        invalidate() // 请求重新绘制视图
    }

    // 设置显示的文字
    fun setText(newText: String) {
        text = newText
        invalidate() // 重新绘制视图以显示新的文字
    }
}